package com.tarena.sentinel.study.demo01.controller;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.tarena.sentinel.study.demo01.service.HelloService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RestController
public class HelloController {

    @Autowired
    private HelloService helloService;

    @GetMapping("/hello")
    public String sayHi(String name){
        // 准备一个sentinel资源入口 Entry
        Entry entry = null;
        String result = null;
        // 对entry赋值 赋值过程会进入到sentinel系统架构计算
        // 提供一个资源名称
        try {
            entry = SphU.entry("sayHi");
            result = helloService.sayHi(name);
        } catch (BlockException e) {
            // entry方法抛出异常 表示入口生成失败，失败原因是sentinel拦截了
            log.info("当前资源sayHi收到了限制",e);
            result = "对不起，你的请求被流量控制啦！";
        }finally {
            if(entry!=null){
                entry.exit();
            }
        }

        return result;
    }

}
